package com.jrx.anytxn.transaction.controller.api;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.data.BusinessRes;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.constant.CouponConstant;
import com.jrx.anytxn.customer.dto.coupon.CouponReq;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.service.ICouponInputService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.customer.service.ITlCouponDetailService;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.common.SendSmsReq;
import com.jrx.anytxn.transaction.service.IActivityLoanService;
import com.jrx.anytxn.transaction.service.ILoanMainInfoService;
import com.jrx.anytxn.transaction.service.ISmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

/**
 * ClassName ActivityLoanController
 *
 * @author lujianyou
 * @version 1.0
 * @description 消费满减活动控制器
 * @date 2021/7/5 1:01
 **/
@Api(tags = "活动-贷款相关接口")
@RestController
@RequestMapping(value = "/api/transaction/activityLoan")
public class ActivityLoanController {
    private static final Logger logger = LoggerFactory.getLogger(ActivityLoanController.class);

    private static final BigDecimal BIG_DECIMAL_99 = new BigDecimal("99");
    private static final BigDecimal BIG_DECIMAL_299 = new BigDecimal("299");
    private static final BigDecimal BIG_DECIMAL_499 = new BigDecimal("499");
    private static final BigDecimal BIG_DECIMAL_999 = new BigDecimal("999");

    @Autowired
    private IActivityLoanService activityLoanService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ILoanMainInfoService loanMainInfoService;
    @Autowired
    private ICouponInputService couponInputService;
    @Autowired
    private ISmsService smsService;

    /**
     * 校验并下发优惠券（统计时间范围：当周周一至周四） 统计当周 周一至周四 消费总额， 小于99 提示不满足当前活动条件 大于99 小于
     *
     * @param couponReq
     * @throws TxnBizException
     */
    @ApiOperation(value = "校验并下发优惠券（统计时间范围：当周周一至周四）", notes = "校验并下发优惠券（统计时间范围：当周周一至周四）")
    @PostMapping(value = "/activityHalfOffOfTheWeek")
    public TxnRespResult<BusinessRes> checkAndGrantCouponFromMondayToThursday(@RequestBody CouponReq couponReq) throws Exception {
        TxnRespResult<BusinessRes> result = new TxnRespResult<>();
        try {
            boolean timeInActive = false;
            // 1、判断当前时间是否在 周一：00:00:00 - 周四 23:59:59
            Integer dayOfWeek = DateUtils.getCurrentDayOfWeek();
            if (dayOfWeek > 4) {
                timeInActive = true;
            }
            CustomerRes customer = customerService.getCustomerByChannelAndUserId(couponReq.getChannel(),
                couponReq.getUserId(), couponReq.getTenantId());
            BigDecimal loanSum = loanMainInfoService.sumByCustomerIdAndLoanTypeFromMondayToThursdayCurrentWeek(
                customer.getSecondLevel().getCustomerId(), TransBizConstant.LOAN_TYPE_4, couponReq.getTenantId(), Constants.DEFAULT_PRODTCT_CODE);
            // 如果消费金额达标，下发券
            if (!Objects.isNull(loanSum) && BIG_DECIMAL_299.compareTo(loanSum) <= 0) {
                // 周一至周四
                if (!timeInActive) {
                    return result.getFail(TxnRespCode.ACTIVITY_SUM_TRAN_AMT_REACH_TIME_NOT_WARN.getCode(),
                        TxnRespCode.ACTIVITY_SUM_TRAN_AMT_REACH_TIME_NOT_WARN.getMsg());
                }
                // 周五十点前提示未开抢
                if(dayOfWeek == 5){
                    Calendar calendar = Calendar.getInstance();
                    int curHour24 = calendar.get(Calendar.HOUR_OF_DAY);
                    if(curHour24 < 10){
                        return result.getFail(TxnRespCode.ACTIVITY_SUM_TRAN_AMT_REACH_TIME_NOT_WARN.getCode(),
                                TxnRespCode.ACTIVITY_SUM_TRAN_AMT_REACH_TIME_NOT_WARN.getMsg());
                    }
                }

                List<TlCouponDetail> tlCouponDetails = null;
                try {
                    // 权益发放
                    tlCouponDetails = couponInputService.grantCoupon(couponReq);
                } catch (Exception e) {
                    if (e instanceof TxnBizException) {
                        TxnBizException txnException = (TxnBizException) e;
                        if (Integer.valueOf(TxnRespCode.ACTIVITY_QUANTITY_ZERO.getCode()).equals(txnException.getErrCode())) {
                            throw new TxnBizException(9999, "本期已抢完，感谢参与!");
                        }
                        throw txnException;
                    }
                    throw new TxnBizException(TxnRespCode.SENTINE_EXCEPTION_ERROR);
                }

                try {
                    TlCouponDetail halfOffCoupon = tlCouponDetails.get(0);
                    logger.info("获取最新下发的五折券信息:customerId {} activityId {} rightsId {}", halfOffCoupon.getCustomerId(),halfOffCoupon.getActivityId(),halfOffCoupon.getRightsId());
                    if (null != halfOffCoupon){
                        SendSmsReq req = new SendSmsReq();
                        req.setCustomerId(halfOffCoupon.getCustomerId());
                        req.setChannel(halfOffCoupon.getChannel());
                        req.setTenantId(halfOffCoupon.getTenantId());
                        req.setMobile(halfOffCoupon.getMobile());
                        String currentTimeMillis = System.currentTimeMillis() + "";
                        String seqNo = (int)(Math.random() * 100000) + currentTimeMillis;
                        req.setSeqNo(seqNo);
                        req.setSmsType(CouponConstant.SMS_TYPE_GRANT_COUPON_RIGHTS);
                        req.setLoanId(halfOffCoupon.getRightsName());
                        smsService.sendSmsMq(req);
                    }
                } catch (Exception e) {
                    logger.info("短信发送异常：{}",e);
                }

                return result.getSuccess(new BusinessRes(1000, "恭喜，抢券成功！可在“我的卡券”中查看五折券"));
            } else {
                // 周五-周日
                if(timeInActive){
                    return result.getFail(TxnRespCode.ACTIVITY_COME_ON.getCode(), TxnRespCode.ACTIVITY_COME_ON.getMsg());
                }else {
                    BigDecimal balance = BIG_DECIMAL_299.subtract(loanSum).setScale(2);
                    return result.getFail(TxnRespCode.ACTIVITY_SUM_TRAN_AMT_NOT_REACH_WARN.getCode(),
                            TxnRespCode.ACTIVITY_SUM_TRAN_AMT_NOT_REACH_WARN.getFormatUserTips(balance));
                }

            }
        } catch (TxnException txnException) {
            Integer errorCode = txnException.getErrCode();
            String errMsg = txnException.getErrMsg();
            if(errorCode == 3126){
                errMsg = "您已领取，可在“我的卡券”中查看五折券";
            }
            if(errorCode == 3310){
                errMsg = "抱歉，券已被抢光，下次加油！";
            }
            return result.getFail(errorCode, errMsg);
        }
    }

    /**
     * 月累计消费满99元送会员类月卡权益
     *
     * @param couponReq
     * @throws TxnBizException
     */
    @ApiOperation(value = "月累计消费满99元送会员类月卡权益", notes = "月累计消费满99元送会员类月卡权益")
    @PostMapping(value = "/activitySpendAtLeas99YuanMonthly")
    public TxnRespResult<BusinessRes> activitySpendAtLeas99YuanMonthly(@RequestBody CouponReq couponReq) {
        TxnRespResult<BusinessRes> result = new TxnRespResult<>();
        try {
            activityLoanService.sendCouponByLoanStatMonthly(couponReq, BIG_DECIMAL_99);
        } catch (TxnException txnException) {
            return result.getSuccess(new BusinessRes(txnException.getErrCode(), txnException.getErrMsg()));
        }
        return result.getSuccess(new BusinessRes(1000, null));

    }

    /**
     * 月累计消费满499元送出行类月卡权益
     *
     * @param couponReq
     * @throws TxnBizException
     */
    @ApiOperation(value = "月累计消费满499元送会员类月卡权益", notes = "月累计消费满499元送会员类月卡权益")
    @PostMapping(value = "/activitySpendAtLeas499YuanMonthly")
    public TxnRespResult<BusinessRes> activitySpendAtLeas499YuanMonthly(@RequestBody CouponReq couponReq) {
        TxnRespResult<BusinessRes> result = new TxnRespResult<>();
        try {
            activityLoanService.sendCouponByLoanStatMonthly(couponReq, BIG_DECIMAL_499);
        } catch (TxnException txnException) {
            return result.getSuccess(new BusinessRes(txnException.getErrCode(), txnException.getErrMsg()));
        }
        return result.getSuccess(new BusinessRes(1000, null));
    }

    /**
     * 月累计消费满999元送出行类月卡权益
     *
     * @param couponReq
     * @throws TxnBizException
     */
    @ApiOperation(value = "月累计消费满999元送会员类月卡权益", notes = "月累计消费满999元送会员类月卡权益")
    @PostMapping(value = "/activitySpendAtLeas999YuanMonthly")
    public TxnRespResult<BusinessRes> activitySpendAtLeas999YuanMonthly(@RequestBody CouponReq couponReq) {
        TxnRespResult<BusinessRes> result = new TxnRespResult<>();
        try {
            activityLoanService.sendCouponByLoanStatMonthly(couponReq, BIG_DECIMAL_999);
        } catch (TxnException txnException) {
            return result.getFail(txnException.getErrCode(), txnException.getErrMsg());
        }
        return result.getSuccess(null);
    }

}
